Find Minimum in Rotated Sorted Array

Suppose a sorted array is rotated at some pivot unknown to you beforehand.

(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).

Find the minimum element.

You may assume no duplicate exists in the array.

Solution:

  1. public class Solution {
  2. public int findMin(int[] a) {
  3. return search(a, 0, a.length - 1);
  4. }
  5. int search(int[] a, int lo, int hi) {
  6. // a[] is sorted
  7. if (lo > hi) {
  8. return a[0];
  9. }
  10. int mid = lo + (hi - lo) / 2;
  11. if (mid > 0 && a[mid - 1] > a[mid]) {
  12. return a[mid];
  13. }
  14. if (mid < a.length - 1 && a[mid] > a[mid + 1]) {
  15. return a[mid + 1];
  16. }
  17. if (a[mid] < a[hi]) {
  18. return search(a, lo, mid - 1);
  19. } else {
  20. return search(a, mid + 1, hi);
  21. }
  22. }
  23. }